﻿using Infragistics.Reports;
using Infragistics.Reports.Server;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Sidvall.Reporting
{
    public class Report : Sidvall.Reporting.IReport
    {
        #region Public Members

        public async Task<Stream> ExportAsync(Stream reportStream, RenderingFormat format, IEnumerable<DataSource> dataSources, IEnumerable<Parameter> parameters)
        {
            var stream = new MemoryStream();
            using (var exporter = ServerExporterFactory.CreateExporter(reportStream))
            {
                exporter.DataSources = GetDataSourceValues(dataSources);
                exporter.Parameters = GetParameterValues(parameters);
                switch (format)
                {
                    case Sidvall.Reporting.RenderingFormat.Pdf:
                        exporter.Export(stream, "PDF");
                        break;
                    default:
                        break;
                }
            }
            return await Task.FromResult(stream).ConfigureAwait(false);
        }

        #endregion
        #region Private Members

        #region GetParameterValues

        private IEnumerable<ParameterValue> GetParameterValues(IEnumerable<Parameter> parameters)
        {
            List<ParameterValue> items;
            ParameterValue item;

            items = new List<ParameterValue>();
            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    item = new ParameterValue()
                    {
                        Name = parameter.Name,
                        Value = parameter.Value,
                    };
                    items.Add(item);
                }
            }
            return items;
        }

        #endregion
        #region GetDataSourceValues

        private IEnumerable<DataSourceValue> GetDataSourceValues(IEnumerable<DataSource> dataSources)
        {
            List<DataSourceValue> items;
            DataSourceValue item;

            items = new List<DataSourceValue>();
            if (dataSources != null)
            {
                foreach (var dataSource in dataSources)
                {
                    item = new DataSourceValue()
                    {
                        Name = dataSource.Name,
                        Value = dataSource.Value,
                    };
                    items.Add(item);
                }
            }
            return items;
        }

        #endregion

        #endregion
    }
}
